package fox.framework.rpc.endpoint.netty.client;

import fox.framework.rpc.client.node.event.NodeChannelCloseEvent;
import fox.framework.rpc.context.event.RpcEventPublisher;
import fox.framework.rpc.endpoint.channel.RpcChannel;
import fox.framework.rpc.endpoint.netty.NettyEndpoint;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * @author cuichao
 * @Description: RpcClientEventHandler
 * @Date: create in 2021/2/7 17:27
 */
public class RpcClientEventHandler extends ChannelInboundHandlerAdapter {


    private RpcEventPublisher publisher;

    public RpcClientEventHandler(RpcEventPublisher publisher) {
        this.publisher = publisher;
    }


    /**
     * 触发下线事件
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        Object attr = channel.attr(NettyEndpoint.RPC_CHANNEL_ATTR_KEY).get();

        if(attr  instanceof RpcChannel){
            RpcChannel rpcChannel = ((RpcChannel) channel.attr(NettyEndpoint.RPC_CHANNEL_ATTR_KEY).get());
            NodeChannelCloseEvent event = new NodeChannelCloseEvent(rpcChannel.node());
            publisher.publishEvent(event);
        }
        //super.channelInactive(ctx);
    }
}
